#include <iostream>
#include "linearlist.h"

LinearList::LinearList(int size) : len(0), cap(size), list(new int[size])
{
}

LinearList::LinearList(const LinearList &l) : len(l.len), cap(l.cap), list(new int[l.cap])
{
    memcpy(list, l.list, len * sizeof(int));
}

void LinearList::operator=(const LinearList &l)
{
    len = l.len;
    cap = l.cap;
    list = new int[l.cap];
    memcpy(list, l.list, len * sizeof(int));
}

LinearList::~LinearList()
{
    delete[] list;
}

const int *LinearList::List() { return list; }
int LinearList::Len() { return len; }
int LinearList::Cap() { return cap; }

void LinearList::Sort()
{
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (list[i] > list[j])
            {
                int temp = list[i];
                list[i] = list[j];
                list[j] = temp;
            }
        }
    }
}

void LinearList::Display()
{
    for (int i = 0; i < len; i++)
    {
        std::cout << list[i] << ", ";
    }
    std::cout << std::endl;
}

bool LinearList::Append(int num)
{
    if (len >= cap)
    {
        return false;
    }
    list[len] = num;
    len++;
    return true;
}

bool LinearList::Insert(int index, int num)
{
    if (len >= cap)
    {
        return false;
    }
    for (int i = len - 1; i >= index; i--)
    {
        list[i + 1] = list[i];
    }
    list[index] = num;
    len++;
    return true;
}

bool LinearList::isIndexValid(int index)
{
    return index <= len - 1 && index >= 0;
}

bool LinearList::Delete(int index)
{
    if (!isIndexValid(index))
    {
        return false;
    }
    for (int i = index; i < len - 1; i++)
    {
        list[i] = list[i + 1];
    }
    len--;
    return true;
}

int LinearList::Index(int index)
{
    if (isIndexValid(index))
    {
        return list[index];
    }
    return -1;
}

int LinearList::Query(int num)
{
    for (int i = 0; i < len; i++)
    {
        if (num == list[i])
        {
            return i;
        }
    }
    return -1;
}

bool LinearList::IsOverflow()
{
    return len > cap;
}